import {ONLOADING, AUTH_SUCCESS, AUTH_FAIL, AUTH } from '../actionTypes'
import { buttons } from '../api'
import {serialize} from "../utils/http";

export function onLoading() {
    return {
        type: ONLOADING
    }
}
export function authSuccess(json) {
    return {
        type: AUTH_SUCCESS,
        json
    }
}

export function authFail(error) {
    return {
        type: AUTH_FAIL,
        error: error
    }
}

export function authAction(rule) {
    return async (dispatch, getState) => {
        let state = getState()
        if(state.isloading !== undefined && state.isloading) {
            return
        }
        dispatch(onLoading())
        fetch(buttons + '?' + serialize({ rule }), {
            method:'GET',
        }).then(response => response.json())
            .then(json => {
                if(json.code === 0 || json.code === '0'){
                    dispatch(authSuccess(json.data))
                }else {
                    dispatch(authFail(json.msg))
                }
            }).catch(err => {
                dispatch(authFail(err))
        })
    }
}

export function authAddAction(params) {
    return {
        url: '/auth/add',
        method: 'POST',
        params: params,
        types: [AUTH, AUTH_SUCCESS, AUTH_FAIL, ONLOADING],
        success: (res, next) => {
            if (Number(res.code) === 0) {

            } else {
                next({
                    type: AUTH_FAIL,
                    loading:  false,
                    error: res.msg,
                });
            }
        }
    };
}
export function authEditAction(params) {
    return {
        url: '/auth/edit',
        method: 'POST'
    }
}
